<script setup lang="ts">
import { reactive, ref } from 'vue'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
// @ts-ignore
import { ReadClients, WriteClients } from '@/Urls/AxiosHelper'

const router = useRouter()
const writeClient = WriteClients[3]
const readClient = ReadClients[3]

// 后端文档接口路径
const API_CREATE_ROUTE = '/productwrite/api/ProcessRoute/CreateProcessRoute'
const API_CREATE_PROCESS_BATCH = '/productwrite/api/Process/BatchProcess'
const API_CREATE_PRODUCT_REL_BATCH = '/productwrite/api/ProductProcess/BatchProductProcess'

const formRef = ref()
const form = reactive({
  processRouteNumber: '',
  autoCode: false,
  processRouteName: '',
  status: true,
  description: '',
  remarks: '',
})

const rules = {
  processRouteNumber: [{ required: true, message: '请输入工艺路线编号', trigger: 'blur' }],
  processRouteName: [{ required: true, message: '请输入工艺路线名称', trigger: 'blur' }],
}

function generateGuid(){
  const buf = new Uint8Array(16)
  crypto.getRandomValues(buf)
  const s = [...buf].map(b=>b.toString(16).padStart(2,'0'))
  s[6] = (parseInt(s[6],16) & 0x0f | 0x40).toString(16)
  s[8] = (parseInt(s[8],16) & 0x3f | 0x80).toString(16)
  return `${s[0]}${s[1]}${s[2]}${s[3]}-${s[4]}${s[5]}-${s[6]}${s[7]}-${s[8]}${s[9]}-${s[10]}${s[11]}${s[12]}${s[13]}${s[14]}${s[15]}`
}

function handleAuto(){
  if(form.autoCode){
    form.processRouteNumber = generateGuid()
    // 清除验证状态
    formRef.value?.clearValidate('processRouteNumber')
  }else{
    form.processRouteNumber = ''
  }
}

async function handleSave(){
  // @ts-ignore
  formRef.value?.validate(async (ok:boolean)=>{
    if(!ok) return
    try{
      const payload = {
        processRouteNumber: form.processRouteNumber,
        processRouteName: form.processRouteName,
        status: form.status,
        description: form.description,
        remarks: form.remarks,
      }
      const res = await writeClient.post(API_CREATE_ROUTE, payload)
      if(res && (res.status===200 || res?.data?.code===200 || res?.data?.success)){
        // 2) 批量提交工序组成（后端接收：{ command, processRouteNumber, processList: ProcItem[] }）
        try{
          console.log('准备提交工序，processList.value:', processList.value)
          const processListWithDelete = processList.value.map(proc => ({
            processNumber: proc.processNumber,
            serialNumber: String(proc.serialNumber), // 转换为字符串
            processName: proc.processName,
            nextProcess: proc.nextProcess || '',
            relationship: proc.relationship || '',
            isCriticalProcess: proc.isCriticalProcess || false,
            preparationTime: proc.preparationTime || 0,
            waitingTime: proc.waitingTime || 0,
            remarks: proc.remarks || '',
            isDelete: false
          }))
          console.log('提交工序数据:', { command: 'BatchProcess', processRouteNumber: form.processRouteNumber, processList: processListWithDelete })
          await writeClient.post(API_CREATE_PROCESS_BATCH, {
            command: 'BatchProcess', // 添加必需的 command 字段
            processRouteNumber: form.processRouteNumber,
            processList: processListWithDelete,
          })
          console.log('工序提交成功')
        }catch(err){ console.warn('提交工序失败', err) }

        // 3) 批量提交关联产品（后端接收：{ processRouteNumber, entity: [{ productNumber }] }）
        try{
          const body = {
            processRouteNumber: form.processRouteNumber,
            entity: relatedProductNumbers.value.map(productNumber => ({
              productNumber
            }))
          }
          await writeClient.post(API_CREATE_PRODUCT_REL_BATCH, body)
        }catch(err:any){ console.warn('提交关联产品失败', err?.response?.data || err) }

        ElMessage.success('保存成功')
        router.push({ name: 'ProcessRouteInfo' })
      }else{ throw new Error(res?.data?.message || '保存失败') }
    }catch(err:any){
      ElMessage.error(err?.response?.data?.message || err?.message || '保存失败')
    }
  })
}

function handleCancel(){ router.push({ name: 'ProcessRouteInfo' }) }

// -------------------- 前端：工序组成（本地数组） --------------------
type ProcItem = {
  processNumber: string
  serialNumber: number
  processName: string
  nextProcess?: string
  relationship?: string
  isCriticalProcess?: boolean
  preparationTime?: number
  waitingTime?: number
  remarks?: string
  isDelete?: boolean
}

const processList = ref<ProcItem[]>([])
const processDialogVisible = ref(false)
const procForm = reactive<ProcItem>({
  processNumber: '',
  serialNumber: 1,
  processName: '',
  nextProcess: '',
  relationship: '',
  isCriticalProcess: false,
  preparationTime: 0,
  waitingTime: 0,
  remarks: '',
})

function openAddProcess(){
  Object.assign(procForm, { processNumber: generateGuid(), serialNumber: (processList.value.length||0)+1, processName:'', nextProcess:'', relationship:'', isCriticalProcess:false, preparationTime:0, waitingTime:0, remarks:'', isDelete:false })
  processDialogVisible.value = true
}
function confirmAddProcess(){
  if(!procForm.processName){ ElMessage.error('请输入工序'); return }
  processList.value.push({ ...procForm })
  console.log('添加工序后，processList:', processList.value)
  processDialogVisible.value = false
}
function removeProcess(row: ProcItem){
  processList.value = processList.value.filter(it=>it.processNumber!==row.processNumber)
}

// -------------------- 前端：关联产品（仅缓存产品编号数组；另存展示列表） --------------------
type ProductItem = {
  productNumber: string
  productName: string
  specificationModel?: string
  unit?: string
  productType?: string
  productAttribute?: string
}

const relatedProductNumbers = ref<string[]>([])
const relatedProductsView = ref<ProductItem[]>([])

const prodDialogVisible = ref(false)
const prodLoading = ref(false)
const prodTable = ref<ProductItem[]>([])
const prodPagination = reactive({ pageIndex:1, pageSize:10, total:0 })
const prodQuery = reactive({ keyword:'' })

function openSelectProduct(){ prodDialogVisible.value = true; fetchProducts() }

async function fetchProducts(){
  prodLoading.value = true
  try{
    const res = await readClient.get('/productread/api/Product/ProductShow', {
      params: {
        pageIndex: prodPagination.pageIndex,
        pageSize: prodPagination.pageSize,
        ProductName: prodQuery.keyword || undefined,
      }
    })
    const payload = res?.data ?? {}
    const root = payload.data ?? payload
    const items = root.data ?? root.items ?? root.rows ?? root.list ?? []
    const total = root.total ?? root.totalCount ?? (Array.isArray(items)? items.length : 0)
    prodTable.value = (Array.isArray(items)? items:[]).map((it:any)=>({
      productNumber: it.productNumber ?? it.ProductNumber ?? it.code,
      productName: it.productName ?? it.ProductName ?? it.name,
      specificationModel: it.specificationModel ?? it.SpecificationModel,
      unit: it.unit ?? it.Unit,
      productType: it.productType ?? it.ProductType,
      productAttribute: it.productAttribute ?? it.ProductAttribute,
    }))
    prodPagination.total = total
  }catch{ ElMessage.error('获取产品列表失败') }
  finally{ prodLoading.value=false }
}
function prodPageChange(p:number){ prodPagination.pageIndex=p; fetchProducts() }
function prodSizeChange(s:number){ prodPagination.pageSize=s; prodPagination.pageIndex=1; fetchProducts() }

const prodSelection = ref<ProductItem[]>([])
function onProdSelectionChange(rows:ProductItem[]){ prodSelection.value = rows }
function confirmSelectProduct(){
  if(prodSelection.value.length===0){ ElMessage.error('请选择产品'); return }
  prodSelection.value.forEach(r=>{
    if(!relatedProductNumbers.value.includes(r.productNumber)){
      relatedProductNumbers.value.push(r.productNumber)
      relatedProductsView.value.push({
        productNumber: r.productNumber,
        productName: r.productName,
        specificationModel: r.specificationModel,
        unit: r.unit,
        productType: r.productType,
        productAttribute: r.productAttribute,
      })
    }
  })
  prodDialogVisible.value = false
}
function removeRelatedProduct(row:{ productNumber:string }){
  relatedProductNumbers.value = relatedProductNumbers.value.filter(x=>x!==row.productNumber)
  relatedProductsView.value = relatedProductsView.value.filter(x=>x.productNumber!==row.productNumber)
}
</script>

<template>
  <div class="create-wrap">
    <el-card>
      <div class="header-row">
        <div class="title">新增工艺路线</div>
        <div class="spacer"></div>
      </div>
    </el-card>

    <el-card class="section-card">
      <template #header>
        <div class="section-title">基础信息</div>
      </template>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="120px" class="base-form">
        <div class="grid">
          <div class="col">
            <el-form-item label="工艺路线编号" prop="processRouteNumber">
              <div class="inline">
                <el-input v-model="form.processRouteNumber" placeholder="请输入" />
                <div class="gap-12"></div>
                <el-switch v-model="form.autoCode" @change="handleAuto" />
                <div class="gap-6"></div>
                <span class="muted">系统编号</span>
              </div>
            </el-form-item>
            <el-form-item label="状态">
              <el-radio-group v-model="form.status">
                <el-radio :label="true">启用</el-radio>
                <el-radio :label="false">禁用</el-radio>
              </el-radio-group>
            </el-form-item>
          </div>
          <div class="col">
            <el-form-item label="工艺路线名称" prop="processRouteName">
              <el-input v-model="form.processRouteName" placeholder="请输入" />
            </el-form-item>
          </div>
        </div>
        <el-form-item label="说明">
          <el-input v-model="form.description" type="textarea" :rows="3" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="form.remarks" type="textarea" :rows="3" placeholder="请输入" />
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="section-card">
      <template #header>
        <div class="section-title">工序组成</div>
      </template>
      <div class="op-row">
        <el-button type="primary" @click="openAddProcess">新增</el-button>
      </div>
      <el-table :data="processList" height="220">
        <el-table-column type="index" label="序号" width="80" />
        <el-table-column prop="processNumber" label="工序编号" min-width="200" />
        <el-table-column prop="processName" label="工序" min-width="140" />
        <el-table-column prop="nextProcess" label="下一道工序" min-width="140" />
        <el-table-column prop="relationship" label="关系" min-width="100" />
        <el-table-column prop="isCriticalProcess" label="关键工序" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.isCriticalProcess ? 'danger' : 'info'">{{ scope.row.isCriticalProcess ? '是' : '否' }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="preparationTime" label="准备时间" width="120" />
        <el-table-column prop="waitingTime" label="等待时间" width="120" />
        <el-table-column prop="remarks" label="备注" min-width="160" />
        <el-table-column label="操作" width="100" fixed="right">
          <template #default="scope">
            <el-link type="danger" underline="never" @click="removeProcess(scope.row)">删除</el-link>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <el-card class="section-card">
      <template #header>
        <div class="section-title">关联产品</div>
      </template>
      <div class="op-row">
        <el-button type="primary" @click="openSelectProduct">添加</el-button>
      </div>
      <el-table :data="relatedProductsView" height="220">
        <el-table-column type="index" label="序号" width="80" />
        <el-table-column prop="productNumber" label="产品编号" min-width="140" />
        <el-table-column prop="productName" label="产品名称" min-width="140" />
        <el-table-column prop="specificationModel" label="规格型号" min-width="140" />
        <el-table-column prop="unit" label="单位" width="80" />
        <el-table-column prop="productType" label="产品类型" min-width="120" />
        <el-table-column prop="productAttribute" label="产品属性" min-width="120" />
        <el-table-column label="操作" width="100" fixed="right">
          <template #default="scope">
            <el-link type="danger" underline="never" @click="removeRelatedProduct(scope.row)">移除</el-link>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <el-card class="section-card">
      <div class="op-bottom">
        <el-button size="large" @click="handleCancel">返回</el-button>
        <el-button size="large" type="primary" @click="handleSave">保存</el-button>
      </div>
    </el-card>
    <!-- 工序新增弹窗 -->
    <el-dialog v-model="processDialogVisible" title="新增工序" width="560px">
    <el-form :model="procForm" label-width="100px">
      <el-form-item label="工序编号">
        <el-input v-model="procForm.processNumber" disabled />
      </el-form-item>
      <el-form-item label="序号">
        <el-input-number v-model="procForm.serialNumber" :min="1" />
      </el-form-item>
      <el-form-item label="工序">
        <el-input v-model="procForm.processName" placeholder="请输入" />
      </el-form-item>
      <el-form-item label="下一道工序">
        <el-input v-model="procForm.nextProcess" placeholder="请输入" />
      </el-form-item>
      <el-form-item label="关系">
        <el-input v-model="procForm.relationship" placeholder="请输入" />
      </el-form-item>
      <el-form-item label="关键工序">
        <el-switch v-model="procForm.isCriticalProcess" />
      </el-form-item>
      <el-form-item label="准备时间">
        <el-input-number v-model="procForm.preparationTime" :min="0" />
      </el-form-item>
      <el-form-item label="等待时间">
        <el-input-number v-model="procForm.waitingTime" :min="0" />
      </el-form-item>
      <el-form-item label="备注">
        <el-input v-model="procForm.remarks" type="textarea" :rows="2" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="processDialogVisible=false">取消</el-button>
        <el-button type="primary" @click="confirmAddProcess">确定</el-button>
      </span>
    </template>
    </el-dialog>

    <!-- 关联产品选择弹窗 -->
    <el-dialog v-model="prodDialogVisible" title="添加产品" width="820px">
    <div class="prod-toolbar">
      <el-input v-model="prodQuery.keyword" placeholder="请输入物料编号/名称" class="flt" />
      <el-button @click="fetchProducts" type="primary">查询</el-button>
    </div>
    <el-table :data="prodTable" v-loading="prodLoading" @selection-change="onProdSelectionChange">
      <el-table-column type="selection" width="48" />
      <el-table-column type="index" label="序号" width="70" />
      <el-table-column prop="productNumber" label="产品编号" min-width="120" />
      <el-table-column prop="productName" label="产品名称" min-width="120" />
      <el-table-column prop="specificationModel" label="规格型号" min-width="120" />
      <el-table-column prop="unit" label="单位" width="80" />
      <el-table-column prop="productType" label="产品类型" min-width="100" />
      <el-table-column prop="productAttribute" label="产品属性" min-width="100" />
    </el-table>
    <div class="pagination">
      <el-pagination
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="prodPagination.total"
        :page-sizes="[10,20,30,50]"
        :page-size="prodPagination.pageSize"
        :current-page="prodPagination.pageIndex"
        @size-change="prodSizeChange"
        @current-change="prodPageChange"
      />
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="prodDialogVisible=false">取消</el-button>
        <el-button type="primary" @click="confirmSelectProduct">确定</el-button>
      </span>
    </template>
    </el-dialog>
  </div>
  
</template>

<style scoped>
.create-wrap{ display:flex; flex-direction:column; gap:12px; }
.header-row{ display:flex; align-items:center; }
.title{ font-size:20px; font-weight:700; }
.spacer{ flex:1; }
.section-card{ background:#fff; border-radius:8px; }
.section-title{ text-align:center; color:#606266; }
.base-form{ margin-top:8px; }
.grid{ display:grid; grid-template-columns: 1fr 1fr; column-gap:24px; }
.col{ display:flex; flex-direction:column; gap:12px; }
.inline{ display:flex; align-items:center; }
.gap-12{ width:12px; }
.gap-6{ width:6px; }
.muted{ color:#909399; font-size:12px; }
.op-row{ display:flex; gap:8px; margin-bottom:8px; }
.op-bottom{ display:flex; justify-content:center; gap:16px; }
.prod-toolbar{ display:flex; align-items:center; gap:8px; margin-bottom:8px; }
.flt{ width:260px; }
.pagination{ display:flex; justify-content:flex-end; margin-top:8px; }
</style>

